﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using weikebuluo.DAL;
using System.Collections.Specialized;
using weikeweixin.web.wechat.api.cs;

namespace weikebuluo.web.wechat.api.cs
{
    public class postmessage
    {
        //根据分组进行群发
        public static string postMessage = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
        common common = new common();
        JavaScriptSerializer Jss = new JavaScriptSerializer();

        public postmessage()
        { }

        //#region 文本Json数据
        //public string GetpostJson(string content)
        //{
        //    string postJson = "";

        //    postJson = "{\"filter\":{\"group_id\":\"2\"},\"text\":{\"content\":\""+content+"\"}, \"msgtype\":\"text\"}";
        //    return postJson;
        //}
        //#endregion 文本Json数据

        #region 发送文本
        public string postexttmessage(string wechat_id, string content)
        {
            string respText = "";
            string menuJson = "{\"filter\":{\"group_id\":\"2\"},\"text\":{\"content\":\"" + content + "\"}, \"msgtype\":\"text\"}";
            string accessToken = common.GetAccessToken(wechat_id);
            string url = string.Format(postMessage, accessToken);
            byte[] requestBytes = Encoding.UTF8.GetBytes(menuJson);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = requestBytes.Length;

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(requestBytes, 0, requestBytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//返回来自inertnet的响应

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }

            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);

            return respDic["errcode"].ToString();//发送返回的错误码

        }
        #endregion 发送文本
    }
}